#include "spriteMap.h"

using namespace std;

SpriteMap::SpriteMap() {
}

SpriteMap::~SpriteMap() {
}

SpriteMap::SpriteMap(BITMAP* bmIn) {

	h = 0;
	w = 0;
	vector<int> limitsX, pivotsX;
	int pivotX = -1;

	for( int i = 1 ; i < bmIn->w ; i++ )
	{
		if( getpixel(bmIn,i,0) == makecol32(255,0,0) )
		{
			pivotX = i;
		}else if( getpixel(bmIn,i,0) == makecol32(0,0,0) || i == (bmIn->w-1) )
		{
			limitsX.push_back(i);
			pivotsX.push_back(pivotX);
			pivotX = -1;
			h++;
		}else if( getpixel(bmIn,i,0)!= makecol32(255,255,255) )
		{
			throw("SpriteMap Shit");
		}
	}

	int baseRow = 1, baseCol = 1;
	int pivotY = -1;

	for( int currentRow = 1 ; currentRow < bmIn->h ; currentRow++ )
	{

		if( getpixel(bmIn,0,currentRow) == makecol32(255,0,0) )
		{
			pivotY = currentRow-baseRow;
		}else if( getpixel(bmIn,0,currentRow) == makecol32(0,0,0) || currentRow == (bmIn->h-1) )
		{
			for( int currentCol = 0 ; currentCol < h ; currentCol++  )
			{
				int spriteH, spriteW;
				spriteW = limitsX[currentCol]-baseCol;
				spriteH = currentRow-baseRow+1;

				int px = (pivotsX[currentCol]==-1?spriteW/2:pivotsX[currentCol]-baseCol);
				int py = (pivotY==-1?spriteH/2:pivotY-baseRow);

				BITMAP* spriteBitmap = create_bitmap(spriteW,spriteH);
				blit( bmIn, spriteBitmap, baseCol, baseRow, 0, 0, spriteW, spriteH );
				Sprite sprite(spriteBitmap, px, py);
				map.push_back(sprite);
				baseCol = limitsX[currentCol]+1;
				w++;
			}
			pivotY = -1;
		}else if( getpixel(bmIn,0,currentRow)!= makecol32(255,255,255) )
		{
			throw("SpriteMap Shit");
		}
	}
}

Sprite SpriteMap::getSprite(int wIn, int hIn) {
    if (wIn < 0 || wIn > w || hIn < 0 || hIn > h){
        cout << "el valor de wIn es: " << wIn << " el hIn: " << hIn << " w: " << w << " h: " << h << endl;
        throw("Error en el indice de getSprite");
    }
    return map[wIn + w*hIn];
}
